package info.fastpace.utils;

import info.fastpace.utils.RunnnableDecorator.RunnableDecoratorSimple;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;

public class RunnableSingleInstance extends RunnableDecoratorSimple {

	private final Timer timer;
	private final AtomicBoolean isRequestMade = new AtomicBoolean(false);
	private TimerTask timerTask;

	public RunnableSingleInstance(final java.lang.Runnable runnable) {
		super(runnable);
		timer = new Timer();
	}

	@Override
	public void run() {
		if (!isRequestMade.compareAndSet(false, true) || timerTask != null) {
			return;
		}
		
		assert timerTask == null;
		
		timerTask = new TimerTask() {
			@Override
			public void run() {
				isRequestMade.set(false);
				try {
					getInner().run();
				}catch (Exception e) {
					Config.getLog().w("Error running Runnable", e);
				}finally {
					timerTask = null;
					if (isRequestMade.compareAndSet(true, false)) {
						RunnableSingleInstance.this.run();
					}
				}
			}
		};
		
		timer.schedule(timerTask, 0);
	}


}
